package org.arch_learn.elastic_search.springboot_es.config;

import lombok.extern.java.Log;
import org.apache.http.HttpHost;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.bulk.BackoffPolicy;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;

@Log
@Configuration
public class ElasticSearchConfig {
    @Value("${spring.elasticsearch.jest.uris}")
    private String hostList;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        //解析hostList信息
        String[] hostArr = hostList.split(",");
        //创建HttpHost数组，封装es的主机和端口
        HttpHost[] httpHostArr = new HttpHost[hostArr.length];
        for (int i = 0; i < hostArr.length; i++) {
            httpHostArr[i] = new HttpHost(hostArr[i].split(":")[0], Integer.valueOf(hostArr[i].split(":")[1]), "http");
        }
        return new RestHighLevelClient(RestClient.builder(httpHostArr));
    }

    @Bean
    public BulkProcessor bulkProcessor(RestHighLevelClient client) {
        BulkProcessor bulkProcessor = null;
        try {
            BulkProcessor.Listener listener = new BulkProcessor.Listener() {
                @Override
                public void beforeBulk(long executionId, BulkRequest request) {
                    log.info("Try to insert data number : " + request.numberOfActions());
                }

                @Override
                public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
                    log.info("************** Success insert data number : " + request.numberOfActions() + " , id: " + executionId);
                }

                @Override
                public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
                    log.info("Bulk is unsuccessful : " + failure + ", executionId: " + executionId);
                }
            };

            BiConsumer<BulkRequest, ActionListener<BulkResponse>> bulkConsumer = (request, bulkListener) -> client.bulkAsync(request, RequestOptions.DEFAULT, bulkListener);
            BulkProcessor.Builder builder = BulkProcessor.builder(bulkConsumer, listener);
            //每5000次请求发一次批量操作
            builder.setBulkActions(5000);
            //或者执行单元达到100M
            builder.setBulkSize(new ByteSizeValue(100L, ByteSizeUnit.MB));
            //或者每100秒执行一次
            builder.setFlushInterval(TimeValue.timeValueSeconds(100L));
            //设置并发请求到达10个
            builder.setConcurrentRequests(10);
            //回退策略：重试3次
            builder.setBackoffPolicy(BackoffPolicy.constantBackoff(TimeValue.timeValueSeconds(1L), 3));
            // 注意点：让参数设置生效
            bulkProcessor = builder.build();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                bulkProcessor.awaitClose(100L, TimeUnit.SECONDS);
            } catch (Exception e1) {
                log.info(e1.getMessage());
            }
        }
        return bulkProcessor;
    }
}
